package io.rainforest.rss.service.rssfollow;

import io.rainforest.rss.base.exception.ServiceException;
import io.rainforest.rss.client.vo.follow.RssFollowReq;
import io.rainforest.rss.dao.mapper.RssFollowMapperExt;
import io.rainforest.rss.dao.po.RssFollow;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class FollowService {

    @Autowired
    RssFollowMapperExt rssFollowMapper;

    public void addFollow( RssFollowReq req){
        RssFollow rssFollow = new RssFollow();
        BeanUtils.copyProperties(req,rssFollow);
        String rssLink = req.getRssLink();
        String rssLinkMd5 = DigestUtils.md5DigestAsHex(rssLink.getBytes());
        RssFollow rssFollow1 = rssFollowMapper.selectByPrimaryKey(rssLinkMd5);
        if(rssFollow1!=null){
            throw new ServiceException("已经添加过该订阅。",3001);
        }
        rssFollow.setRssId(rssLinkMd5);
        rssFollow.setCreateTime(System.currentTimeMillis()+0.0);
        rssFollowMapper.insertSelective(rssFollow);
    }

    public List<RssFollow> queryList(RssFollowReq req) {
        RssFollow rssFollow = new RssFollow();
        BeanUtils.copyProperties(req,rssFollow);
        List<RssFollow> list = rssFollowMapper.selectList(rssFollow);
        return list;
    }

    /**
     * 通过 rssId 查询订阅
     * @param rssId
     * @return
     */
    public RssFollow queryOne(String rssId) {
        RssFollow one = rssFollowMapper.selectByPrimaryKey(rssId);
        return one;
    }

    public void updateFollow(RssFollow req) {
        rssFollowMapper.updateByPrimaryKeySelective(req);
    }

    public void deleteFollow(String rssId) {
        rssFollowMapper.deleteByPrimaryKey(rssId);
    }
}
